package com.shawn.mobliesafe;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shawn.bean.AppInfo;
import com.shawn.db.dao.WatchDogDao;
import com.shawn.engine.AppEngine;
import com.shawn.utils.AppUtil;
import com.shawn.utils.DensityUtil;
import com.shawn.utils.MyAsycnTaks;

import java.util.ArrayList;
import java.util.List;

public class SoftMangaerActivity extends AppCompatActivity implements View.OnClickListener{

    private ListView lv_softmanager_application;
    private ProgressBar loading;
    private List<AppInfo> list;
    private List<AppInfo> userappinfo;
    private List<AppInfo> systemappinfo;
    private TextView tv_softmanager_userorsystem;
    private PopupWindow popupWindow;
    private AppInfo appInfo;
    private TextView tv_softmanager_rom;
    private TextView tv_softmanager_sd;
    private WatchDogDao watchDogDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soft_mangaer);

        watchDogDao = new WatchDogDao(this);

        tv_softmanager_rom = (TextView)findViewById(R.id.tv_softmanager_rom);
        tv_softmanager_sd = (TextView)findViewById(R.id.tv_softmanager_sd);
        lv_softmanager_application = (ListView)findViewById(R.id.lv_softmanager_application);
        tv_softmanager_userorsystem = (TextView)findViewById(R.id.tv_softmanager_userorsystem);
        loading = (ProgressBar)findViewById(R.id.loading);

        //获取可用内存
        long availableSD = AppUtil.getAvailableSD();
        long availableROM = AppUtil.getAvailableROM();
        //数据转化
        String sdsize = Formatter.formatFileSize(getApplicationContext(),availableSD);
        String romsize = Formatter.formatFileSize(getApplicationContext(),availableROM);
        //设置显示
        tv_softmanager_sd.setText("SD卡可用:"+sdsize);
        tv_softmanager_rom.setText("内存可用:"+romsize);
        fillData();
        listviewOnscroll();
        listviewItemClick();
        listviewItemLongClick();
    }

    /**
     * 条目长按点击事件
     */
    private void listviewItemLongClick() {
        lv_softmanager_application.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //屏蔽用户和系统程序(..个)不能加锁解锁操作
                if (position == 0 || position == userappinfo.size()+1) {
                    return true;
                }
                //获取数据
                if (position <= userappinfo.size()) {
                    //用户程序
                    appInfo = userappinfo.get(position-1);
                    Log.e("TAG","用户程序");
                }else{
                    //系统程序
                    appInfo = systemappinfo.get(position - userappinfo.size() - 2);
                    Log.e("TAG","系统程序");
                }
                //加锁解锁
                final ViewHolder viewHolder = (ViewHolder) view.getTag();

                //判断应用有没有加锁,有的解锁,没有的加锁
                if(watchDogDao.queryLockApp(appInfo.getPackagName())) {
                    final String pwd = watchDogDao.queryLockPwd(appInfo.getPackagName());
                    //解锁操作
                    Log.e("TAG", "解锁");
                   View pwdview = View.inflate(getApplicationContext(),R.layout.soft_enterpassword,null);
                    final EditText et_setpassword_password = (EditText) pwdview.findViewById(R.id.et_setpassword_password);
                    new AlertDialog.Builder(SoftMangaerActivity.this)

                            .setTitle("软件锁")
                            .setIcon(appInfo.getIcon())
                            .setView(pwdview)
                            .setNegativeButton("解锁", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String password = et_setpassword_password.getText().toString().trim();
                                    if(TextUtils.isEmpty(password)) {
                                        Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    if(!pwd.equals(password)) {
                                        Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    watchDogDao.deleteLockApp(appInfo.getPackagName());
                                    viewHolder.iv_itemsoftmanager_islock.setImageResource(R.mipmap.unlock);
                                    dialog.dismiss();
                                }
                            })
                            .show();

                }else {
                    //加锁操作
                    Log.e("TAG", "加锁");
                    View pwdview = View.inflate(SoftMangaerActivity.this,R.layout.soft_setpassword,null);
                    final EditText et_setpassword_password = (EditText) pwdview.findViewById(R.id.et_setpassword_password);
                    final EditText et_setpassword_confrim = (EditText) pwdview.findViewById(R.id.et_setpassword_confrim);
                    new AlertDialog.Builder(SoftMangaerActivity.this)

                            .setTitle("软件锁")
                            .setIcon(appInfo.getIcon())
                            .setView(pwdview)
                            .setPositiveButton("加锁", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //判断如果是当前应用程序,就不要加锁
                                    if (!watchDogDao.queryLockApp(getPackageName())) {

                                        String password = et_setpassword_password.getText().toString().trim();
                                        String password2 = et_setpassword_confrim.getText().toString().trim();
                                        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(password2)) {
                                            Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        if (!password.equals(password2)) {
                                            Toast.makeText(getApplicationContext(), "两次输入密码不同", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        watchDogDao.addLockApp(appInfo.getPackagName(), password);
                                        viewHolder.iv_itemsoftmanager_islock.setImageResource(R.mipmap.lock);
                                        dialog.dismiss();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "当前的应用程序不能加锁", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            })
                            .show();
                }
                return true;
            }
        });
    }

    /**
     * 条目点击事件
     */
    private void listviewItemClick() {
        lv_softmanager_application.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //1.屏蔽用户程序和系统程序(...个)弹出气泡
                if (position == 0 || position == userappinfo.size() + 1) {
                    return;
                }
                //2.获取条目所对应的应用程序的信息
                //数据就要从userappinfo和systemappinfo中获取
                if(position <= userappinfo.size()) {
                    appInfo = userappinfo.get(position - 1);
                }else {
                    appInfo = systemappinfo.get(position - userappinfo.size() - 2);
                }

                //5.弹出新的气泡之前,删除旧 的气泡
                hidePopuwindow();
                //3.弹出气泡
                View contentView = View.inflate(getApplicationContext(), R.layout.popu_window, null);
                //初始化控件
                LinearLayout ll_popuwindow_uninstall = (LinearLayout) contentView.findViewById(R.id.ll_popuwindow_uninstall);
                LinearLayout ll_popuwindow_start = (LinearLayout) contentView.findViewById(R.id.ll_popuwindow_start);
                LinearLayout ll_popuwindow_share = (LinearLayout) contentView.findViewById(R.id.ll_popuwindow_share);
                LinearLayout ll_popuwindow_detail = (LinearLayout) contentView.findViewById(R.id.ll_popuwindow_detail);
                //给控件设置点击事件
                ll_popuwindow_uninstall.setOnClickListener(SoftMangaerActivity.this);
                ll_popuwindow_start.setOnClickListener(SoftMangaerActivity.this);
                ll_popuwindow_share.setOnClickListener(SoftMangaerActivity.this);
                ll_popuwindow_detail.setOnClickListener(SoftMangaerActivity.this);

                //contentView : 显示view对象
                //width,height : view宽高
                popupWindow = new PopupWindow(contentView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                //4.获取条目的位置,让气泡显示在相应的条目
                int[] location = new int[2];//保存x和y坐标的数组
                view.getLocationInWindow(location);//获取条目x和y的坐标,同时保存到int[]
                //获取x和y的坐标
                int x = location[0];
                int y = location[1];
                //parent : 要挂载在那个控件上
                //gravity,x,y : 控制popuwindow显示的位置
                popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, x + DensityUtil.px2dip(SoftMangaerActivity.this,50), y);

                //6.设置动画
                //缩放动画
                //前四个 :　控制控件由没有变到有   动画 0:没有    1:整个控件
                //后四个:控制控件是按照自身还是父控件进行变化
                //RELATIVE_TO_SELF : 以自身变化
                //RELATIVE_TO_PARENT : 以父控件变化
                ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF,
                        0, Animation.RELATIVE_TO_SELF, 0.5f);
                scaleAnimation.setDuration(500);
                AlphaAnimation alphaAnimation = new AlphaAnimation(0.4f, 1.0f);
                alphaAnimation.setDuration(500);
                //组合动画
                //shareInterpolator : 是否使用相同的动画插补器  true:共享    false:各自使用各自的
                AnimationSet animationSet = new AnimationSet(true);
                animationSet.addAnimation(scaleAnimation);
                animationSet.addAnimation(alphaAnimation);
                contentView.startAnimation(animationSet);
            }
        });
    }

    /**
     * 隐藏气泡
     */
    private void hidePopuwindow() {
        if(popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //隐藏气泡
        hidePopuwindow();
    }
    /**
     * listview滑动监听事件
     */
    private void listviewOnscroll() {
        lv_softmanager_application.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            //view : listview
            //firstVisibleItem : 界面第一个显示条目
            //visibleItemCount : 显示条目总个数
            //totalItemCount : 条目的总个数
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                hidePopuwindow();
                if (userappinfo != null && systemappinfo != null) {
                    if (firstVisibleItem >= userappinfo.size() + 1) {
                        tv_softmanager_userorsystem.setText("系统程序(" + systemappinfo.size() + ")");
                    } else {
                        tv_softmanager_userorsystem.setText("用户程序(" + userappinfo.size() + ")");
                    }
                }
            }
        });
    }

    /**
     * 加载数据
     */
    private void fillData() {
        new MyAsycnTaks(){

            @Override
            public void preTask() {
                loading.setVisibility(View.VISIBLE);
            }

            @Override
            public void doinBack() {
                list = AppEngine.getAppInfos(SoftMangaerActivity.this);
                userappinfo = new ArrayList<AppInfo>();
                systemappinfo = new ArrayList<AppInfo>();
                for (AppInfo appInfo : list){
                    if(appInfo.isUser()) {
                        userappinfo.add(appInfo);
                    }else {
                        systemappinfo.add(appInfo);
                    }
                }
            }

            @Override
            public void postTask() {
                lv_softmanager_application.setAdapter(new Myadapter());
                loading.setVisibility(View.INVISIBLE);
            }
        }.execute();
    }

    @Override
    public void onClick(View v) {
        //判断点击是按个按钮
        //getId() : 获取点击按钮的id
        switch (v.getId()) {
            case R.id.ll_popuwindow_uninstall:
                uninstall();
                break;
            case R.id.ll_popuwindow_start:
                start();
                break;
            case R.id.ll_popuwindow_share:
                share();
                break;
            case R.id.ll_popuwindow_detail:
                detail();
                break;
        }
        hidePopuwindow();
    }
    /**
     *详情
     */
    private void detail() {
        /**
         *  Intent
         {
         act=android.settings.APPLICATION_DETAILS_SETTINGS    action
         dat=package:com.example.android.apis   data
         cmp=com.android.settings/.applications.InstalledAppDetails
         } from pid 228
         */
        Intent intent = new Intent();
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.parse("package:" + appInfo.getPackagName()));
        startActivity(intent);
    }

    /**
     * 分享
     */
    private void share() {
        /**
         *  Intent
         {
         act=android.intent.action.SEND
         typ=text/plain
         flg=0x3000000
         cmp=com.android.mms/.ui.ComposeMessageActivity (has extras)   intent中包含信息
         } from pid 228
         */
        Intent shareIntent = new Intent();
        shareIntent.setAction("android.intent.action.SEND");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my Share text.");
        shareIntent.setType("text/plain");

        //设置分享列表的标题，并且每次都显示分享列表
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    /**
     * 启动
     */
    private void start() {
        PackageManager pm = getPackageManager();
        //获取应用程序的启动意图
        Intent intent = pm.getLaunchIntentForPackage(appInfo.getPackagName());
        if(intent != null) {
            startActivity(intent);
        }else {
            Toast.makeText(getApplicationContext(), "系统核心程序,无法启动", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 卸载
     */
    private void uninstall() {
        /**
         * <intent-filter>
         <action android:name="android.intent.action.VIEW" />
         <action android:name="android.intent.action.DELETE" />
         <category android:name="android.intent.category.DEFAULT" />
         <data android:scheme="package" />
         </intent-filter>
         */
        //判断是否是系统程序
        if(appInfo.isUser()) {
            //判断是否是我们自己的应用,是不能卸载
            if(!appInfo.getPackagName().equals(getPackageName())) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.DELETE");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse("package" + appInfo.getPackagName()));
                startActivityForResult(intent, 0);
            }else {
                Toast.makeText(getApplicationContext(), "文明社会,杜绝自杀", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(getApplicationContext(), "要想卸载系统程序,需要root权限", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        fillData();
    }

    private class Myadapter extends BaseAdapter {

        @Override
        public int getCount() {
            return userappinfo.size()+systemappinfo.size()+2;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(position == 0) {
                TextView textView = new TextView(SoftMangaerActivity.this);
                textView.setBackgroundColor(Color.GRAY);
                textView.setTextColor(Color.WHITE);
                textView.setText("用户程序("+userappinfo.size()+")");
                return textView;
            }else if(position == userappinfo.size()+1) {
                TextView textView = new TextView(SoftMangaerActivity.this);
                textView.setBackgroundColor(Color.GRAY);
                textView.setTextColor(Color.WHITE);
                textView.setText("系统程序(" + systemappinfo.size()+")");
                return textView;
            }

            View view;
            ViewHolder viewHolder;
            if(convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }else {
                view = View.inflate(SoftMangaerActivity.this,R.layout.item_softmanager,null);
                viewHolder = new ViewHolder();
                viewHolder.iv_itemsoftmanage_icon = (ImageView) view.findViewById(R.id.iv_itemsoftmanage_icon);
                viewHolder.tv_softmanager_name = (TextView) view.findViewById(R.id.tv_softmanager_name);
                viewHolder.tv_softmanager_version = (TextView) view.findViewById(R.id.tv_softmanager_version);
                viewHolder.tv_softmanager_issd = (TextView) view.findViewById(R.id.tv_softmanager_issd);
                viewHolder.iv_itemsoftmanager_islock = (ImageView) view.findViewById(R.id.iv_itemsoftmanager_islock);
                view.setTag(viewHolder);
            }
            AppInfo appInfo = null;
            if(position <= userappinfo.size()) {
                appInfo = userappinfo.get(position-1);
            }else {
                appInfo = systemappinfo.get(position - userappinfo.size() - 2);
            }
            viewHolder.iv_itemsoftmanage_icon.setImageDrawable(appInfo.getIcon());
            viewHolder.tv_softmanager_name.setText(appInfo.getName());
            boolean sd = appInfo.isSD();
            if(sd) {
                viewHolder.tv_softmanager_issd.setText("SD卡");
            }else {
                viewHolder.tv_softmanager_issd.setText("手机内存");
            }
            viewHolder.tv_softmanager_version.setText(appInfo.getVersionName());
            //判断应用程序是加锁还是解锁
            if (watchDogDao.queryLockApp(appInfo.getPackagName())) {
                //加锁
                viewHolder.iv_itemsoftmanager_islock.setImageResource(R.mipmap.lock);
            }else{
                //解锁
                viewHolder.iv_itemsoftmanager_islock.setImageResource(R.mipmap.unlock);
            }
            return view;
        }
    }
    static class ViewHolder{
        ImageView iv_itemsoftmanage_icon,iv_itemsoftmanager_islock;
        TextView tv_softmanager_name,tv_softmanager_issd,tv_softmanager_version;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(popupWindow != null) {
                hidePopuwindow();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
